<template>
  <div class="etfNotion">
    <div style="height: 250px; background: linear-gradient(0deg, white -5.77%, #e1ebff 141%)"></div>
    <div class="search">
      <div class="search-title">
        <span> 查询概念板块进行匹配反查 </span>
      </div>
      <div class="search-input">
        <el-select
          ref="mySelect"
          v-model="searchValue"
          reserve-keyword
          filterable
          remote
          placeholder="输入概念板块"
          auto-complete="off"
          :remote-method="remoteMethod"
          @change="handleSearchValueChange"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <!-- <div style="position: absolute; left: 706px; top: 72px; z-index: 10">
          <el-button @click="toggleDropdown">查询</el-button>
        </div> -->
      </div>
      <!-- <div class="search-history">
        <svg-icon name="clock"></svg-icon>
        查询历史：
        <span v-for="(item, index) in history" :key="index"> {{ item }} </span>
      </div> -->
    </div>
    <div class="idea-plate">
      <div class="idea-plate-title">
        <div class="idea-plate-icon"></div>
        <span class="font-black">概念板块收益表现</span>
        <div
          v-show="!isShowPlateTable"
          @click="isShowPlateTable = !isShowPlateTable"
          style="cursor: pointer"
        >
          <Icon icon="iconamoon:arrow-right-2-thin" width="24" height="24" />
        </div>
        <div
          v-show="isShowPlateTable"
          @click="isShowPlateTable = !isShowPlateTable"
          style="cursor: pointer"
        >
          <Icon icon="iconamoon:arrow-down-2-thin" width="24" height="24" />
        </div>
      </div>

      <div class="idea-plate-content pb-4">
        <plate-content v-show="isShowPlateTable" @clickName="queryByName"></plate-content>
      </div>
    </div>
    <!-- 概念指数成分股 -->
    <div class="divide-y-2">
      <index-stock
        :sectcode="searchValue"
        :label="selectedLabel"
        v-if="selectedLabel"
        @change-label="changeLabel"
      ></index-stock>
      <div v-if="selectedLabel">
        <div class="flex-col items-start">
          <div class="search-result-title">
            <div class="search-result-icon"></div>
            <span class="font-black">与</span>
            <span class="font-blue">
              “{{
                (() => {
                  const startIndex = selectedLabel.indexOf('(')
                  return startIndex !== -1
                    ? selectedLabel.substring(0, startIndex).trim()
                    : selectedLabel
                })()
              }}”
            </span>
            <span class="font-black"> 相似的指数 </span>
          </div>
          <div class="flex my-3 ml-56">
            <div class="text-sm text-[#333333] flex items-center">
              含有概念股数量比例
              <IconSort class="ml-1 cursor-pointer" @click="handleSort('sectCoverRate')" />
            </div>
            <div class="text-sm text-[#333333] flex items-center ml-20">
              含有概念股权重
              <IconSort class="ml-1 cursor-pointer" @click="handleSort('sectCoverWeight')" />
            </div>
            <el-tooltip
              effect="light"
              content="概念指数与该ETF指数过去1年日涨跌幅的相关系数*100%"
              placement="top"
              popper-class="atooltip"
            >
              <div class="text-sm text-[#333333] flex items-center ml-20">
                与概念指数走势相关性
                <IconSort class="ml-1 cursor-pointer" @click="handleSort('sectRelation')" />
              </div>
            </el-tooltip>
          </div>
        </div>
        <div
          class="search-result"
          v-infinite-scroll="loadMore"
          :infinite-scroll-disabled="disabled"
          :infinite-scroll-distance="200"
          style="overflow-y: auto; max-height: 60vh"
        >
          <div class="result-list" v-for="(item, index) in resultList" :key="index">
            <div class="result-item-title">
              <div class="result-item">
                <div class="result-item-title">
                  <span>{{ item.sIrdname }}</span>
                </div>
                <div class="result-item-content">
                  <div class="content-title">
                    <span class="content-title-left"> 指数代码 </span>
                    <span class="content-title-right">{{ item.sIrdcode }}</span>
                  </div>
                  <div class="content-title">
                    <span class="content-title-left">含有概念股数量比例 </span>
                    <span class="content-title-right">{{
                      formattedSectRelation(item.sectCoverRate)
                    }}</span>
                  </div>
                  <div class="content-title">
                    <span class="content-title-left">含有概念股权重 </span>
                    <span class="content-title-right">{{
                      formattedSectRelation(item.sectCoverWeight)
                    }}</span>
                  </div>
                  <div class="content-title" style="display: flex">
                    <span class="content-title-left">与概念指数走势相关性 </span>
                    <el-progress
                      :percentage="item.sectRelation ? (item.sectRelation * 100).toFixed(2) : 0"
                    ></el-progress>
                  </div>
                </div>
              </div>
              <div class="result-btn" @click="showTable(item)">
                <!--  :disabled="item?.detailsList?.length === 0" -->
                <el-button type="text"
                  >{{ item.isActive ? '收起' : '展开' }}查看跟踪ETF
                  <span v-if="item.isActive">({{ item?.detailsList?.length }})</span>
                </el-button>
                <!-- :disabled="item?.detailsList?.length === 0" -->
                <el-button type="text" v-if="!item.isActive">
                  <Icon icon="iconamoon:arrow-right-2-thin" width="24" height="24" />
                </el-button>
                <!-- :disabled="item?.detailsList?.length === 0" -->
                <el-button type="text" v-else>
                  <Icon icon="iconamoon:arrow-down-2-thin" width="24" height="24" />
                </el-button>
                <!--  -->
              </div>
            </div>
            <div class="result-table" v-show="item?.detailsList?.length > 0 && item.isActive">
              <el-table
                :ref="(el: HTMLElement | null) => setTableRef(item.sIrdcode, el)"
                :data="item?.detailsList"
                style="width: 100%"
                stripe
                @selection-change="(rows: SelectedRow[]) => resultSelectionChange(rows, item)"
                row-key="sIrdCode"
                reserve-selection
              >
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="sIrdCode" label="ETF代码" align="center" min-width="110">
                  <template #default="scope">
                    <span
                      class="text-[#2468f2] cursor-pointer"
                      @click="toFundDetail(scope?.row?.sIrdCode)"
                      >{{ scope?.row?.sIrdCode }}</span
                    >
                  </template>
                </el-table-column>
                <el-table-column prop="abbrName" label="ETF简称" align="center" min-width="140">
                </el-table-column>
                <el-table-column
                  prop="managementComp"
                  label="基金公司"
                  align="center"
                  min-width="140"
                >
                </el-table-column>
                <el-table-column prop="managerName" label="基金经理" align="center" min-width="140">
                </el-table-column>
                <el-table-column prop="idxType2" label="基金类型" align="center" min-width="110">
                </el-table-column>
                <el-table-column prop="netAsset" label="基金规模" align="center" min-width="110">
                  <template #default="scope">
                    <span>{{ formatNetAsset(scope?.row?.netAsset) }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="setUpDt" label="基金成立日" align="center" min-width="110">
                </el-table-column>
                <el-table-column
                  prop="trackingError"
                  label="跟踪误差"
                  align="center"
                  min-width="110"
                >
                  <template #header>
                    <el-tooltip effect="light" placement="top" :raw-content="true">
                      <template #content>
                        <div class="formula-tooltip" v-html="renderFormula(trackingErrorFormula)" />
                      </template>
                      <span>跟踪误差</span>
                    </el-tooltip>
                  </template>
                  <template #default="scope">
                    <span>{{ fix2(scope?.row?.trackingError) }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="sIndexIrdCode"
                  label="跟踪指数代码"
                  align="center"
                  min-width="110"
                >
                  <template #default="scope">
                    <span
                      class="text-[#2468f2] cursor-pointer"
                      @click="toTrackDetail(scope?.row)"
                      >{{ scope?.row?.sIndexIrdCode }}</span
                    >
                  </template>
                </el-table-column>
                <el-table-column
                  prop="sIrdName"
                  label="跟踪指数名称"
                  align="center"
                  min-width="110"
                >
                </el-table-column>
                <el-table-column
                  prop="iopvDiscountRate"
                  label="IOPV溢折率"
                  align="center"
                  min-width="110"
                >
                  <template #header>
                    <el-tooltip
                      class="item"
                      effect="light"
                      popper-class="tooltip-class-blue"
                      content="IOPV溢折率=（二级市场价格/基金份额净值-1)×100%"
                      placement="top"
                    >
                      <span>IOPV溢折率</span>
                    </el-tooltip>
                  </template>
                  <template #default="scope">
                    <span>{{ fix2(scope?.row?.iopvDiscountRate) }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="volumeMa20"
                  label="20日日均成交额"
                  align="center"
                  min-width="150"
                >
                  <template #default="scoped">
                    <span>
                      {{ formatAmount(scoped?.row?.volumeMa20 * 1000) }}
                    </span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
          <!-- 加载状态提示 -->
          <div v-if="loading" class="loading-text">加载中...</div>
          <div v-if="noMore" class="no-more-text">没有更多数据了</div>
        </div>
        <div
          style="
            height: 70px;
            background-color: rgb(255, 255, 255);
            position: fixed;
            bottom: 0px;
            z-index: 50;
            left: 196px;
            right: 0px;
            max-width: 1300px;
            margin: 0px auto;
          "
          class="flex justify-end items-center"
        >
          <div class="flex items-center mr-6 gap-4">
            <span
              >共选 <span class="text-[#2468f2]"> {{ selectedFundList.length }} </span> 条基金</span
            >
            <div class="cursor-pointer">
              <el-popover placement="top" :width="240" trigger="click">
                <template #reference>
                  <span class="text-[#2468f2] ml-2 mr-1">
                    详情
                    <el-icon :size="14" :color="'#2468f2'"> <ArrowUp /> </el-icon
                  ></span>
                </template>
                <el-table :data="selectedFundList" height="204" :show-header="false">
                  <el-table-column property="abbrName" label="abbrName" />
                  <el-table-column width="50">
                    <template #default="{ row }">
                      <el-button type="text" @click.stop="handleDeleteFund(row)" class="p-0">
                        <Icon icon="ep:delete" width="18" height="18" />
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-popover>
            </div>
          </div>
          <div>
            <el-button type="primary" @click="toPortfolioCreate">添加到模拟组合</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, computed, provide, onMounted, nextTick } from 'vue'
import PlateContent from './plateContent.vue'
import IndexStock from './indexStock.vue'
import { getW1055046, getW1055048, getHanger } from '@/api/etfpegging.js'
import { Icon } from '@iconify/vue'
import routerParent from '@/utils/router/routerParent/index'
import IconSort from '@/assets/img/sort.svg?component'
import katex from 'katex'
import 'katex/dist/katex.min.css'
import sensors from '@/utils/sensor/index'
import { ElMessage } from 'element-plus'
interface SelectedRow {
  sIrdCode: string
  abbrName: string
}

const changeLabel = (val: string) => {
  getW1055048Data(val)
}
// 删除
const handleDeleteFund = async (fund: SelectedRow) => {
  // 从选中列表移除
  selectedFundList.value = selectedFundList.value.filter((f) => f.sIrdCode !== fund.sIrdCode)
  selectedFundCodes.value.delete(fund.sIrdCode)

  // 遍历所有结果项
  for (const item of resultList.value) {
    // 查找包含该基金的指数项
    const targetRow = item.detailsList.find((d) => d.sIrdCode === fund.sIrdCode)
    if (targetRow) {
      nextTick(() => {
        const table = tableRefs.value[item.sIrdcode]
        table?.toggleRowSelection(targetRow, false)
      })
    }
  }
}

// 初始化选中列表
const selectedFundList = ref<SelectedRow[]>([])
const selectedFundCodes = ref<Set<string>>(new Set())

onMounted(() => {})
// Add a flag to track programmatic selection
const isProgrammaticSelection = ref(false)

// 修改后的resultSelectionChange方法
const resultSelectionChange = (selectedRows: SelectedRow[], item: ResultItem) => {
  // Skip processing if this is triggered by programmatic selection
  if (isProgrammaticSelection.value) {
    return
  }
  // 创建临时Set提高查询性能
  const currentSelections = new Set(selectedRows.map((r) => r.sIrdCode))

  // 更新全局选中列表（新增项）
  selectedRows.forEach((row) => {
    if (!selectedFundCodes.value.has(row.sIrdCode)) {
      selectedFundCodes.value.add(row.sIrdCode)
      selectedFundList.value.push(row)
    }
  })

  // 更新全局选中列表（移除项）
  item.detailsList.forEach((row) => {
    if (!currentSelections.has(row.sIrdCode) && selectedFundCodes.value.has(row.sIrdCode)) {
      selectedFundCodes.value.delete(row.sIrdCode)
      selectedFundList.value = selectedFundList.value.filter((f) => f.sIrdCode !== row.sIrdCode)
    }
  })
}
const tableRefs = ref<Record<string, any>>({})

const setTableRef = (key: string, el: any) => {
  if (el) tableRefs.value[key] = el
}
//携带数据跳转到组合创建页面
const toPortfolioCreate = () => {
  if (selectedFundList.value.length === 0) {
    ElMessage.warning('请先选择要添加的组合信息！')
    return
  }
  const encodedFundList = encodeURIComponent(JSON.stringify(selectedFundList.value))
  routerParent(`/portfolioCreate?selectedFundLists=${encodedFundList}`)
}
interface ResultItem {
  sIrdname: string
  sIrdcode: string
  sectRelation: number
  sectCoverWeight: number
  sectCoverRate: number
  isActive: boolean
  detailsList: Array<any>
}
//接收子组件点击概念名称
const queryByName = (val: { sSectcode: string; sSectname: string }) => {
  //重新给下来options赋值
  options.value = [
    {
      value: val.sSectcode,
      label: val.sSectname,
    },
  ]
  searchValue.value = val.sSectcode
  selectedLabel.value = val.sSectname
  isShowPlateTable.value = false
  getW1055048Data(searchValue.value)
}

const trackingErrorFormula = String.raw`
{\color{#2468f2}基金误差 = \sqrt{\frac{1}{N-1}\sum{_{t=1}^{N}}\left(基金日度收益率-跟踪指数日度收益率 \right) ^2}\times\sqrt{252}}
`
const renderFormula = (formula: string) => {
  try {
    return katex.renderToString(formula, {
      throwOnError: false,
      displayMode: true,
      output: 'mathml',
    })
  } catch (e) {
    console.error('KaTeX render error:', e)
    return formula
  }
}

//排序相关
const orderField = ref('') // 排序字段
const orderFlag = ref(0) // 排序标识 0-降序 1-升序
const handleSort = (field: string) => {
  console.log('rph-------field', field)
  if (orderField.value === field) {
    orderFlag.value = orderFlag.value === 0 ? 1 : 0
  } else {
    orderField.value = field
    orderFlag.value = 0
  }

  // 重置分页
  pageNum.value = 1
  resultList.value = []
  getW1055048Data(searchValue.value)
}

const resultList = ref<ResultItem[]>([])
const searchValue = ref('')
interface Option {
  value: string
  label: string
}

//跳转到基金详情
const toFundDetail = (code: string) => {
  routerParent(`/EtfFundDetails?sIrdCode=${code}`)
}

interface Row {
  sIndexIrdCode: string
  sIrdName: string
}

const toTrackDetail = (row: Row) => {
  const sIndexIrdCode = row.sIndexIrdCode
  const sIrdname = row.sIrdName
  routerParent(`/trackerDetail?sIrdCode=${sIndexIrdCode}&sIrdName=${encodeURIComponent(sIrdname)}`)
}
const options = ref<Option[]>([])
const isShowPlateTable = ref(true)
const selectedLabel = ref('')

// 新增分页相关变量
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const disabled = computed(() => loading.value || noMore.value)
const noMore = computed(() => resultList.value.length >= total.value)
const formatAmount = (val: any) => {
  if (val == null) return '--'

  const formatWithCommas = (num: any) => {
    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
  }

  if (val >= 1e8) return formatWithCommas((val / 1e8).toFixed(2)) + '亿'
  if (val >= 1e4) return formatWithCommas((val / 1e4).toFixed(2)) + '万'
}

const fix2 = (val: any) => {
  if (val === 0) return '0'
  if (!val) return '--'
  return (val * 100).toFixed(2) + '%'
}
const formatNetAsset = (val: any) => {
  if (!val) return '--'
  return (val / 100000000).toFixed(2) + '亿'
}

const formattedSectRelation = (sectRelation: any) => {
  return sectRelation ? `${(sectRelation * 100).toFixed(2)}%` : '--'
}
import { useLabelStore } from '@/stores/etfPeggingStore/labelStore'
const dataSource = useLabelStore()
const dataSourceMap = {
  'WD': '万得',
  'DZH': '大智慧'
};
const remoteMethod = (query: any) => {
  if (query !== '') {
    console.log('rph-----query', query)
    sensors.track('zhitou_etfpegging_search', {
      button_name: 'ETF反查搜索',
    })
  }
  if (query !== '') {
    const params = {
      searchContent: query,
      dataSource: '',
    }
    getW1055046(params).then((res: any) => {
      if (res && res.data) {
        options.value = res.data.map((item: any) => {
          return {
            value: item.sSectcode,
            label: `${item.sSectname}(${dataSourceMap[item.dataSource as keyof typeof dataSourceMap]})`,
          }
        })
      }
    })
  } else {
    options.value = []
  }
}

const handleSearchValueChange = (value: any) => {
  const selectedOption = options.value.find((option) => option.value === value)
  if (selectedOption) {
    selectedLabel.value = selectedOption.label
    isShowPlateTable.value = false
  } else {
    selectedLabel.value = ''
  }
}

const getW1055048Data = async (query: any) => {
  loading.value = true
  try {
    const params = {
      sSectcode: query,
      currentPage: pageNum.value,
      pageSize: pageSize.value,
      orderField: orderField.value,
      orderFlag: orderFlag.value,
    }
    const res = await getW1055048(params)
    if (res?.data) {
      total.value = res.data.total
      const newData = res.data.records.map((item: any) => ({
        ...item,
        isActive: false,
        detailsList: [],
      }))
      if (pageNum.value === 1) {
        resultList.value = newData
      } else {
        resultList.value = [...resultList.value, ...newData]
      }
    }
  } finally {
    loading.value = false
  }
}

// 无限滚动加载方法
const loadMore = () => {
  if (noMore.value || !searchValue.value) return
  pageNum.value++
  getW1055048Data(searchValue.value)
}

// 修改后的showTable方法
const showTable = async (item: ResultItem) => {
  item.isActive = !item.isActive

  if (item.isActive && !item.detailsList.length) {
    try {
      const res = await getHanger({ sIrdCode: item.sIrdcode })
      item.detailsList = res.data || []

      nextTick(() => {
        const table = tableRefs.value[item.sIrdcode]
        if (table) {
          // Set flag before programmatic selections
          isProgrammaticSelection.value = true
          // 先清空当前页选中
          table.clearSelection()

          // 同步全局选中状态到当前表格
          item.detailsList.forEach((row) => {
            if (selectedFundCodes.value.has(row.sIrdCode)) {
              table.toggleRowSelection(row, true)
            }
          })
        }
      })
      // Reset flag after selections are complete
      nextTick(() => {
        isProgrammaticSelection.value = false
      })
    } catch (error) {
      console.error('Error loading ETF data:', error)
    }
  }
}

// 修改搜索值变化处理
watch(searchValue, (newVal) => {
  if (newVal) {
    pageNum.value = 1 // 重置页码
    total.value = 0 // 重置总数
    getW1055048Data(newVal)
  } else {
    resultList.value = []
  }
})

watch(options, (newVal) => {
  if (newVal) {
    options.value = newVal
  }
})
</script>

<style lang="scss" scoped>
.atooltip {
  background: #000 !important;
  /*背景色  !important优先级*/
  color: #2468f2;
  /*字体颜色*/
}

.etfNotion {
  position: relative;
  height: 100vh;
  min-height: max-content;
}

.search {
  position: absolute;
  top: 115px;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  .search-title {
    margin-bottom: 24px;

    span {
      font-family: Source Han Sans CN;
      font-size: 32px;
      font-weight: 700;
      text-underline-position: from-font;
      color: #3f598c;
    }
  }

  .search-history {
    margin-top: 16px;
    color: #33333366;
  }

  :deep(.el-select__wrapper.is-filterable) {
    height: 50px;
    width: 800px;
    border-radius: 100px;
  }

  .search-input {
    :deep(.el-button--medium) {
      width: 88px;
      height: 42px;
      margin-top: 4px;
      background: #2468f2;
      border-radius: 100px;
      color: #fff;
    }
  }
}

.idea-plate {
  margin: 12px 20px;

  .idea-plate-title {
    display: flex;
    align-items: center;
    margin-bottom: 12px;

    .idea-plate-icon {
      width: 6px;
      height: 19px;
      background: #2468f2;
      border-radius: 3px;
      margin-right: 8px;
    }

    .font-black {
      font-family: Source Han Sans CN;
      font-size: 18px;
      font-weight: 500;
      color: #000;
    }
  }
}

.search-result-title {
  margin: 12px 20px;
  display: flex;
  align-items: center;

  .search-result-icon {
    width: 6px;
    height: 19px;
    background: #2468f2;
    border-radius: 3px;
    margin-right: 8px;
  }

  .font-black {
    font-family: Source Han Sans CN;
    font-size: 18px;
    font-weight: 500;
    color: #000;
  }

  .font-blue {
    font-family: Source Han Sans CN;
    font-size: 18px;
    font-weight: 500;
    color: #2468f2;
  }
}

.search-result {
  //overflow-y: scroll;
  margin: 0 20px;

  .result-list {
    background: linear-gradient(360deg, #ffffff 50%, #f1f6ff 100%);
    border: 1px solid #dde6f6;
    border-radius: 8px;
    justify-content: space-between;
    margin-bottom: 20px;

    .result-item-title {
      display: flex;
      justify-content: space-between;

      .result-item {
        .result-item-title {
          span {
            margin: 10px 0px 4px 10px;
            font-family: Source Han Sans CN;
            font-size: 18px;
            font-weight: 500;
            color: #2468f2;
          }
        }

        .result-item-content {
          display: flex;
          margin: 0 0 10px 10px;

          .content-title {
            margin-right: 40px;

            .content-title-left {
              font-family: Source Han Sans CN;
              font-size: 14px;
              font-weight: 350;
              margin-right: 4px;
              color: #7b7f8d;
            }

            .content-title-right {
              font-family: Source Han Sans CN;
              font-size: 14px;
              font-weight: 500;

              color: #333333;
            }
          }

          :deep(.el-progress) {
            display: flex;
            align-items: center;
            width: 220px;
          }
        }
      }

      .result-btn {
        display: flex;
        height: 30px;
        margin: 20px 20px;
        align-items: center;

        :deep(.el-button:hover) {
          border-color: transparent;
          background-color: transparent;
        }

        :deep(.el-button:focus) {
          color: #2468f2;
          border-color: transparent;
          background-color: transparent;
        }
      }
    }

    .result-table {
      margin: 15px 10px;
    }
  }
}

/* 新增样式 */
.loading-text,
.no-more-text {
  padding: 10px;
  text-align: center;
  color: #999;
}
</style>
<style>
.atooltip {
  color: #2468f2;
  /*字体颜色*/
  font-size: 13px;
}

.tooltip-class-blue {
  color: #2468f2;
  font-size: 13px;
}
</style>
